export default class Base {
  constructor(router) {
    this.router = router;
    this.current = this.createRoute(null, { path: "/" });
  }
  // 路径跳转 所有的跳转逻辑都要跳转到transitionTo中进行实现
  transitionTo(location, cb) {
    // 根据路径拿到对应的组件
    let record = this.router.match(location);
    // 每次都是更新current 监听current进行更新
    let route = this.createRoute(record, { path: location });
    // 当路由切换的时候也应该拿到新的路径进行渲染
    // 当前路由和切换路由进行对比
    if (
      location === this.current.path &&
      route.matched.length === this.current.matched.length
    ) {
      return;
    }
    const queue = [].concat(this.router.beforeHooks);
    this.runQueue(queue, this.current, route, () => {
      this.current = route;
      cb && cb();
      this.cb && this.cb(route);
    });
  }
  runQueue(queue, from, to, cb) {
    function next(index) {
      if (index >= queue.length) {
        cb();
      } else {
        if (queue[index]) {
          queue[index](from, to, () => {
            next(index + 1);
          });
        } else {
          next(index + 1);
        }
      }
    }
    next(0)
  }
  // 如果是多个路径组成需要进行拆分
  createRoute(record, location) {
    const matched = [];
    if (record) {
      while (record) {
        matched.unshift(record);
        record = record.parent;
      }
    }
    return {
      ...location,
      matched,
    };
  }
  // 自定义钩子
  listen(cb) {
    // 在这边进行调用钩子
    this.cb = cb;
  }
}
